package com.jinly.ryder.ansible.service.impl;

import com.jinly.ryder.ansible.service.model.AnsibleTask;
import com.jinly.ryder.ansible.service.model.AnsibleTaskProgress;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.zeroturnaround.exec.stream.LogOutputStream;

import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Slf4j
@Getter
@RequiredArgsConstructor
public class AnsibleOutputStream extends LogOutputStream {
    private final List<AnsibleTask> taskList;
    private final Consumer<AnsibleTaskProgress> consumer;


    private List<String> resultType = List.of("ok", "changed", "skipping", "fatal");

    @Override
    protected void processLine(String line) {
        if (line.startsWith("TASK [")) {
            String taskName = LineUtil.get(line, "[", "]");
            for (int i = 0; i < taskList.size(); i++) {
                if (taskList.get(i).getName().equals(taskName)) {
                    taskList.get(i).setRun(true);
                    consumer.accept(new AnsibleTaskProgress(taskName, ((double) (i + 1) / taskList.size()) * 100));
                    break;
                }
            }
        } else {
            for (String type : resultType) {
                if (line.startsWith(type)) {
                    List<AnsibleTask> runningTaskList = taskList.stream().filter(t -> t.isRun()).collect(Collectors.toList());
                    if (runningTaskList.size() > 0) {
                        runningTaskList.get(runningTaskList.size() - 1).setResult(type);
                    }
                    break;
                }
            }
        }
    }
}
